package com.emser.unc.activitys;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Toast;

import com.emser.unc.R;
import com.emser.unc.activitys.resources.Constant;
import com.emser.unc.database.dao.SaleReportDataSource;
import com.emser.unc.restlet.manager.SaleReportTransferManager;
import com.emser.unc.serializable.SaleReportDTO;

@SuppressLint("HandlerLeak")
public class EndSaleActivity extends Activity implements OnClickListener,
		Runnable {
	
	private Button btnBack;
	private Button btnNext;
	private Button btnFinish;
	private Button btnSave;
	private Button btnCancel;
	private ProgressDialog progressDialog;
	private SaleReportDataSource reportDataSource;
	private Boolean dispatched;
	private Handler handler;
	private AlertDialog alertDialog;
	
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.p_end_sale);
        initWidgets();
        initDatasource();
        initHandler();
        addDialogListener();
    }
	
	private void initWidgets() {
		 btnBack = (Button) findViewById(R.id.buttonBack);
	        btnNext = (Button) findViewById(R.id.buttonNext);
	        btnBack.setOnClickListener(this);
	        btnNext.setTextColor(Color.GRAY);
	        btnNext.setClickable(false);
	        btnFinish = (Button) findViewById(R.id.buttonSend);
	        btnFinish.setOnClickListener(this);
	        btnSave = (Button) findViewById(R.id.buttonSave);
	        btnSave.setOnClickListener(this);
	        btnCancel = (Button) findViewById(R.id.buttonCancel);
	        btnCancel.setOnClickListener(this);
	        alertDialog = new AlertDialog.Builder(this).create();
	}
	
	private void initDatasource() {
		reportDataSource = new SaleReportDataSource(this);
		reportDataSource.open();
		dispatched = Boolean.FALSE;
	}
	
	@Override
	protected void onResume() {
		reportDataSource.open();
		super.onResume();
	}

	@Override
	protected void onPause() {
		reportDataSource.close();
		super.onPause();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unbindDrawables(findViewById(R.id.EndSaleView));
	    System.gc();
	}
	
	private void unbindDrawables(View view) {
		if (view.getBackground() != null) {
			view.getBackground().setCallback(null);
		}
		if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
			for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
				unbindDrawables(((ViewGroup) view).getChildAt(i));
			}
			((ViewGroup) view).removeAllViews();
		}
	}
	
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			Intent intent = new Intent(EndSaleActivity.this, OrderActivity.class);
			intent.putExtra("idReport",getIntent().getLongExtra("idReport", -1));
			intent.putExtra("sellerName", getIntent().getStringExtra("sellerName"));
			intent.putExtra("customerId", getIntent().getLongExtra("customerId", -1));
			startActivity(intent);
			finish();
			return true;
		default:
			return super.onKeyUp(keyCode, event);
		}
	}
	
	private void initHandler() {
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				progressDialog.dismiss();
				switch (msg.what) {
				case Constant.H_SEND_CASE:
//					if(dispatched){
						reportDataSource.setSent(getIntent().getLongExtra("idReport", -1));
						alertDialog.setMessage("Enviado con exito");
						alertDialog.show();
//					}
//					else{
//						alertDialog.setMessage("Fallo en envio: Reintente");
//						alertDialog.show();
//					}
					break;
				case Constant.H_ERROR_CASE:
					 alertDialog
					 .setMessage(getString(R.string.login_alert_dialog_error));
					 alertDialog.show();
					break;
				default:
					super.handleMessage(msg);
					break;
				}
				dispatched = Boolean.FALSE;
			}
		};
	}
	
	private void addDialogListener() {
		alertDialog.setButton(getString(R.string.login_alert_dialog_button),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						finish();
					}
				});
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.buttonBack:
			Intent intent = new Intent(EndSaleActivity.this, OrderActivity.class);
			intent.putExtra("idReport",getIntent().getLongExtra("idReport", -1));
			intent.putExtra("sellerName", getIntent().getStringExtra("sellerName"));
			intent.putExtra("customerId", getIntent().getLongExtra("customerId", -1));
			startActivity(intent);
			finish();
			break;
		case R.id.buttonSend:
			sendNoSaleReport();
//			SaleReportDTO sr = reportDataSource.getSaleReport(getIntent().getLongExtra("idReport", -1));
//			System.out.println(">>>>>>>> idReport: "+sr.getIdReport());
//			System.out.println(">>>>>>>> customerID: "+sr.getCustomerID());
//			System.out.println(">>>>>>>> sellerUserName: "+sr.getSellerUserName());
//			System.out.println(">>>>>>>> amount: "+sr.getAmount());
//			System.out.println(">>>>>>>> List<ProductSoldDTO>: "+sr.getProductsSold().toString());
//			reportDataSource.setSent(getIntent().getLongExtra("idReport", -1));
			break;
		case R.id.buttonSave:
			reportDataSource.setPending(getIntent().getLongExtra("idReport", -1));
			Toast.makeText(this, "Guardado en Pendientes ", Toast.LENGTH_LONG).show();
			finish();
			break;
		case R.id.buttonCancel:
			reportDataSource.deleteSaleReport(getIntent().getLongExtra("idReport", -1));
			finish();
			break;	
		default:
			break;
		}
		
	}
	
	private void sendNoSaleReport(){
		progressDialog = ProgressDialog.show(EndSaleActivity.this,
				getString(R.string.report_process_dialog_title),
				getString(R.string.report_process_dialog_get), true, false);
		Thread thread = new Thread(this);
		thread.start();
	}
	
	private void startSaleTransfer()throws Exception {
		SaleReportDTO sr = reportDataSource.getSaleReport(getIntent().getLongExtra("idReport", -1));
		SaleReportTransferManager stm = new SaleReportTransferManager();
		stm.setParams(getString(R.string.restlet_url_sale),
				getString(R.string.restlet_user),
				getString(R.string.restlet_pass));
		ExecutorService executor = Executors.newSingleThreadExecutor();
		Future<String> future = executor.submit(stm);
		stm.setRequest(sr);
		future.get(30, TimeUnit.SECONDS);
		dispatched = (Boolean) stm.getResponse();
		System.out.println("------------------- El Boolean es: "+dispatched);
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			startSaleTransfer();
			System.out.println("LLEGADA AL INSTANT");
			handler.sendEmptyMessage(Constant.H_SEND_CASE);
		} catch (Exception e) {
			System.out.println("SALIDA AL INSTANT");
			handler.sendEmptyMessage(Constant.H_ERROR_CASE);
		}
	}

}
